package com.ygqh.baby.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.ProductStatus;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.controller.utils.DocumentHandler;
import com.ygqh.baby.model.StockModel;
import com.ygqh.baby.po.*;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.shiro.utils.SessionUtil;
import com.ygqh.baby.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/admin/stock")
public class StockController extends BaseController<Object, Long> {
    private String stock_key = "stock_sync";
    @Autowired
    private YgStockService ygStockService;
    @Autowired
    private YgStockWhiteListService ygStockWhiteListService;
    @Autowired
    private YgSkuService ygSkuService;
    @Autowired
    private YgProductService ygProductService;
    @Autowired
    private RedisDao redisDao;
    @Autowired
    private KsdStockService ksdStockService;
    @Autowired
    private FileService fileService;

    @RequestMapping("searchStock")
    @ResponseBody
    public Map<String, Object> searchStock(String q, QueryInfo queryInfo, Long groupId, String productName, String productCode, String skuCode, Long amount,
                                           Long supplierId, boolean isPre) {
        ResultSet<YgStock> resultSet = null;
        if (supplierId == 1)
            resultSet = ygStockService.search(queryInfo, q, groupId, productName, productCode, skuCode, amount, isPre);
        else
            resultSet = ksdStockService.search(queryInfo, q, groupId, productName, productCode, skuCode, amount);
        return resultSet.toDatatables(null);
    }

    @RequestMapping("searchStockV2")
    @ResponseBody
    public Map<String, Object> searchStockV2(String q, QueryInfo queryInfo, ProductStatus productStatus, String productName, String productCode, String skuCode,
                                             Long amount, Long supplierId, boolean isPre, Boolean isSync, String adminProductName, String barCode) {
        ResultSet<StockModel> resultSet = ygStockService.searchV2(queryInfo, q, productStatus, productName, productCode, skuCode, amount, supplierId, isPre,
                isSync, adminProductName, barCode);
        return resultSet.toDatatables(null);
    }

    @RequestMapping("setStockWhite")
    @ResponseBody
    public Message setStockWhite(String productIds) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("productIds", productIds);
        // 根据ProductIds 获取SkuCode
        if (productIds.length() > 1) {
            String skuCodes = ygSkuService.getSkuCodes(productIds);
            map.put("skuCodes", skuCodes);
        } else {
            map.put("skuCodes", "");
        }
        redisDao.set(stock_key, JSONObject.toJSONString(map), 0);

        return SUCCESS_MESSAGE;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("findStockWhite")
    @ResponseBody
    public Message findStockWhite() {
        String str = redisDao.get(stock_key);
        Map<String, String> map = JSONObject.parseObject(str, Map.class);
        // 根据productIds 获取产品信息
        String productIds = map.get("productIds");
        if (map.size() > 0 && !productIds.equals("")) {
            String[] arr = productIds.split(",");
            Long[] ids = new Long[arr.length];
            for (int i = 0; i < arr.length; i++) {
                ids[i] = Long.valueOf(arr[i]);
            }
            List<YgProduct> list = ygProductService.findByIds(ids);
            return Message.success(list);
        }
        return Message.success(null);

    }

    @RequestMapping("getStockWhiteById")
    @ResponseBody
    public Message getStockWhiteById(Long id) {
        YgStockWhiteList white = ygStockWhiteListService.findById(id);
        return Message.success(white);
    }

    @RequestMapping("getStockByProductId")
    @ResponseBody
    public Message getStockByProductId(Long productId, Long supplierId) {
        List<YgSku> p = null;
        if (supplierId == 1)
            p = ygStockService.findByProductId(productId);
        else
            p = ksdStockService.findByProductId(productId);
        return Message.success(p);

    }

    @RequestMapping("updateStock")
    @ResponseBody
    public Message updateWholesalePrice(String stocks, Long supplierId) {
        AdminUser user = SessionUtil.getCurrentUser();
        List<YgStock> list = JsonUtils.toObject(stocks, new TypeReference<List<YgStock>>() {
        });
        for (YgStock ygStock : list) {
            ygStock.setUpdateBy(user.getTrueName());
            ygStock.setUpdateTime(new Date());
        }
        ygStockService.updateBatch(list, user.getTrueName(), null);
        return SUCCESS_MESSAGE;
    }

    @RequestMapping("setSync")
    @ResponseBody
    public Message setSync(String skuCode, Boolean sync) {
        ygStockService.setSync(skuCode, sync);
        return SUCCESS_MESSAGE;
    }

    @RequestMapping("fullySyncStockFromWdt")
    @ResponseBody
    public Message fullySyncStockFromWdt() {
        return ygStockService.fullySyncStockFromWdt();
    }

    @RequestMapping("syncStockFromWdt")
    @ResponseBody
    public Message syncStockFromWdt(String... skuCode) {
        return ygStockService.syncStockFromWdt(skuCode);
    }

    @RequestMapping("exportStock")
    public void exportStock(String q, ProductStatus productStatus, String productName, String productCode, String skuCode,
                            Long amount, Long supplierId, Boolean isPre, Boolean isSync, String adminProductName, String barCode, HttpServletRequest request, HttpServletResponse response) throws IOException {
        QueryInfo queryInfo = new QueryInfo();
        queryInfo.setEnd(2000000);
        List<StockModel> list = ygStockService.getStockList(queryInfo, q, productStatus, productName, productCode, skuCode, amount, supplierId, isPre, isSync, adminProductName, barCode);
        byte[] bytes = fileService.downloadFromOss("template/yiigoo_stock_template.xlsx");
        List<Map<String, Object>> dataMaps = new ArrayList<Map<String, Object>>();
        Map<String, Object> dataMap = new HashMap<String, Object>();

        dataMap.put("resultSet2", list);
        dataMaps.add(dataMap);
        DocumentHandler.DownloadExcel(bytes, "商品库存.xlsx", dataMap, request, response);
    }
}
